package com.adlotto2.android.activity.info;

import org.w3c.dom.Element;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Process;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.adlotto2.android.R;
import com.adlotto2.android.activity.LottoAdMainActivity;
import com.adlotto2.android.common.BaseActivity;
import com.adlotto2.android.cronos.http.CNLottoAdApiSet;
import com.adlotto2.android.cronos.http.CNLottoAdApiSetEx;
import com.adlotto2.android.util.ApplicationUtils;
import com.adlotto2.android.util.CNCronosLog;
import com.adlotto2.android.util.LottoAdConstants;
import com.adlotto2.android.util.LottoAdOverButton;

/**
 * 주소,성별 선택 Activity
 * @author Administrator
 *
 */
public class LottoAdInfoAdressActivity extends BaseActivity{
	
	/**요청 Activity 구분 Index**/
	private final int REQUEST_ACTIVITY_ADRESS = 0;
	private final int REQUEST_ACTIVITY_INFO2 = 1;
	
	private Context mContext;
	
	/**다음 버튼*/
	private Button mNextBtn;
	/**남 버튼*/
	private Button mManBtn;
	/**여 버튼*/
	private Button mWomanBtn;
	
	/**성별*/
	private String mGender;
	/**주소*/
	private String mAddress;
	/**나이대*/
	private int mAge;
	/**관심분야*/
	private String mFavorite;
	/**직업*/
	private int mJobsSeq;
	/**상세 주소*/
	private String mSido;
	private String mGugun;
	private String mDong;
	
	/**푸쉬 토큰*/
	private String mPushToken;
	/**단말기 전화번호*/
	private String mPhoneNum;
	
	/**회원가입 성공여부*/
	private boolean mJoinSucess;
	
	// 추천인 ID
	private String mRecommenderId;
	
	/**주소 목록 버튼*/
	private Button mLocationBtn;
	
	/**최상위 뷰*/
	private View rootView;
	
	/**주소선택 확인*/
	private boolean mIsAddrSelect = false;
	/**성별선택 확인*/
	private boolean mIsGenderSelect = false;
	
	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_info_adress;
	}

	@Override
	protected void onInit() {
		this.mContext = this;
		
		mPhoneNum = ApplicationUtils.getPhoneNumber(mContext);
		rootView = getWindow().getDecorView().findViewById(android.R.id.content);
		
		mManBtn = (Button) findViewById(R.id.button_man);
		mWomanBtn = (Button) findViewById(R.id.button_woman);
		mLocationBtn = (Button) findViewById(R.id.button_location);
		mNextBtn = (Button) findViewById(R.id.button_next);
		
		mLocationBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, LottoAdAdressListActivity.class);
				startActivityForResult(intent, REQUEST_ACTIVITY_ADRESS);
			}
		});
		
		mManBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mIsGenderSelect = true;
				mManBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.service_select_male));
				mWomanBtn.setBackgroundDrawable(null);
				mGender = "m";
			}
		});
		
		mWomanBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mIsGenderSelect = true;
				mManBtn.setBackgroundDrawable(null);
				mWomanBtn.setBackgroundDrawable(getResources().getDrawable(R.drawable.service_select_female));
				mGender = "w";
			}
		});
		
		mNextBtn.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Drawable getBackground = v.getBackground();
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					v.setBackgroundDrawable(LottoAdOverButton.grayimg(getBackground));
				}
				else if(event.getAction() == MotionEvent.ACTION_UP){
					getBackground.clearColorFilter();
					v.setBackgroundDrawable(getBackground);
					if(mIsAddrSelect && mIsGenderSelect){
						Intent intent = new Intent(mContext, LottoAdInfoGenerationActivity.class);
						startActivityForResult(intent, REQUEST_ACTIVITY_INFO2);
					} else {
						ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), getString(R.string.location_doNotSelected));
					}
				}
				return false;
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == REQUEST_ACTIVITY_ADRESS && resultCode == RESULT_OK){
			mIsAddrSelect = true;
			mAddress = data.getStringExtra("address");
			mSido = data.getStringExtra("sido");
			mGugun = data.getStringExtra("gugun");
			mDong = data.getStringExtra("dong");
			mLocationBtn.setText(mAddress);
		}
		
		else if(requestCode == REQUEST_ACTIVITY_INFO2 && resultCode == RESULT_OK){
			rootView.setVisibility(View.INVISIBLE);
			
			mJoinSucess = true;
			CNCronosLog.d("onActivityResult",mAddress);
			CNCronosLog.d("onActivityResult",mGender);
			CNCronosLog.d("onActivityResult",String.valueOf(data.getIntExtra("generation",0)));
			mAge = data.getIntExtra("generation",0);
			CNCronosLog.d("onActivityResult",String.valueOf(data.getIntExtra("jobs", 0)));
			mJobsSeq = data.getIntExtra("jobs", 0);
			CNCronosLog.d("onActivityResult",data.getStringExtra("favorite"));
			
			mFavorite = data.getStringExtra("favorite");
			mRecommenderId = ApplicationUtils.getStrPreferences(this, "recommenderId");
			if(mRecommenderId.length() == 0) {
				mRecommenderId = null;
			}
			
			CNCronosLog.d("onActivityResult",ApplicationUtils.getStrPreferences(mContext, LottoAdConstants.PREFER_REGISTRATION_ID));
			mPushToken = ApplicationUtils.getStrPreferences(mContext, LottoAdConstants.PREFER_REGISTRATION_ID);
			
			
			if(mPushToken != null && mPushToken.length()>0){
				if(mPhoneNum != null &&!mPhoneNum.equals("0") && !mPhoneNum.equals(""))
					onRequestData();
				else{
					ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), "전화번호를 수집하는데 실패하였습니다.\n 전화번호(USIM)가 없으면 서비스를 이용 하실 수 없습니다.",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									Process.killProcess(0);
									finish();
								}
							});
				}
			}
			else {
				ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.popup_alert), "PushToken을 수집하는데 실패하였습니다.\nPushToken이 없으면 서비스를 이용 하실 수 없습니다.",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Process.killProcess(0);
						finish();
					}
				});
			}
		}
	}
	
	@Override
	public String onGetAsyncRequestUrl() {
		CNCronosLog.d("onGetAsyncRequestUrl()");
		String url = null;
		
		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		/*####### Ben ########*/
		// 마지막 변수 채워주세용
		if(!CNLottoAdApiSet.isLive()) {
			Log.e("BenTag", "Recommender id : (" + mRecommenderId + ")");
		}
		url = MnetGlobalApiSetEx.setMemberUrl(mContext, mAge, mGender, mSido, mGugun, mDong, mPhoneNum, mJobsSeq, mFavorite, mPushToken, mRecommenderId);
		CNCronosLog.d("onGetAsyncRequestUrl", "url : "+url);
		return url;
	}
	
	@Override
	public void onAsyncCancelRequest() 
	{
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncCancelRequest()");
	}

	@Override
	public void onAsyncDataError(Element xmlObject, String errorMessage)
	{
		super.hideLoadingDialog();
		
		/*ApplicationUtils.showOkDialog(mContext, 0, "알림", errorMessage);*/
		new AlertDialog.Builder(mContext).
		setTitle("알림").
		setMessage("회원가입 오류로 인해 프로그램을 종료합니다.").
		setPositiveButton("확인", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
			}
		}).show();
	}

	@Override
	public void onAsyncPreRequest()
	{
		super.showLoadingDialog();
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject)
	{
		super.hideLoadingDialog();
		
		try {
			parseStoreList(xmlObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onAsyncRequestError(int errorNumber) {
		super.hideLoadingDialog();
		
		ApplicationUtils.showOkDialog(mContext,0,getString(R.string.popup_alert), ApplicationUtils.getErrorMessage(mContext, errorNumber));
	}
	
	private void parseStoreList(Element xmlObject) throws Exception
	{
		
		if(mJoinSucess){ // 회원가입 성공 메인액티비티로 이동
			ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.register_title), getString(R.string.register_success_contents),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						Intent intent = new Intent(mContext, LottoAdMainActivity.class);
						intent.putExtra("join", true);
						startActivity(intent);
						finish();
						ApplicationUtils.setBoolPreferences(mContext, LottoAdConstants.PREPERENCE_IS_REGISTER, true);
					}
				});
		} else {
			ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.register_title), getString(R.string.register_fail_contents));
		}
	}
}
